﻿<?php
// $Id$

/**
 * Controller_Enterprise 控制器
 */
class Controller_Enterprise extends Controller_Abstract
{

    function actionIndex()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }

        $user = $this->_app->currentUserObject();
        if(1 != $user->permission_id)
        {
            return $this->_redirect(url('default/index'));
        }

        // 分页查询
        $page = intval($this->_context->page);
        if ($page < 1) $page = 1;
        // 构造查询对象
        $select = Enterprise::find('enterprise_id <> 1 AND enterprise_status = 1')->order('enterprise_id DESC')->all();
        $select->limitPage($page, 10);

        // 将分页信息和查询到的数据传递到视图
        $this->_view['pagination'] = $select->getPagination();
        $this->_view['enterprises'] = $select->getAll();
        $this->_viewname = 'index';
    }

    function actionDelete()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }

        $user = $this->_app->currentUserObject();
        if(1 != $user->permission_id)
        {
            return $this->_redirect(url('default/index'));
        }
        //企业用户的数据是否保留
        //修改企业用户状态为0
        if(isset($_POST['checkboxid']))
        {
            $id=$_POST['checkboxid'];

            foreach ($id as $value)
            {
                $enterprise = Enterprise::find('enterprise_id = ?', $value)->query();
                $enterprise->enterprise_status=0;
                $enterprise->save();
            }
        }

        return $this->_redirect(url('enterprise/index'));
    }

    function actionAdd()
    {

        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }

        $user = $this->_app->currentUserObject();
        if(1 != $user->permission_id)
        {
            return $this->_redirect(url('default/index'));
        }

        // 构造表单对象
        $form = new Form_EnterpriseAdd(url('enterprise/add')); 

        if ($this->_context->isPOST() && $form->validate($_POST))
        {
            //dump($_POST);
            try
            {
                $enterprise = new Enterprise($form->values());
                $enterprise->enterprise_status = 1;
		$web_site=Q::ini('appini/web_site_ip');
                $default_logo = $web_site. $this->_context->baseDir(). '/static/const_img/telecom_logo.png';
                $enterprise->enterprise_logo = $default_logo;
                $enterprise->save();

                require_once '_code/lib/constant.php';
                $enterprise_dir = $this->_app->config('ROOT_DIR') . PREFIX_UPLOAD_ENTERPRISE . "/$enterprise->enterprise_id";
                if(!file_exists($enterprise_dir))
                {
                    mkdir($enterprise_dir, 0777);
                }
                chmod($enterprise_dir, 0777);
                return $this->_redirect(url('enterprise/index'));
            }
            catch(Exception $ex)
            {
                return $this->_redirectMessage(
                    '添加的企业'.$_POST['enterprise_name'].'已经存在',
                    '请录入其他企业',
                    url('enterprise/add'));

            }
        }

        // 将表单对象传递给视图
        $this->_view['form'] = $form;

        $this->_viewname = 'Add';
    }

    function actionEdit()
    {
        if(null == $this->_app->currentUser())
        {  
            return $this->_redirect(url('default/index'));
        }

        $user = $this->_app->currentUserObject();
        if(1 != $user->permission_id)
        {
            return $this->_redirect(url('default/index'));
        }

        $enterprise = Enterprise::find('enterprise_id = ?', $this->_context->enterprise_id)->query();

        // 构造表单对象
        $form = new Form_EnterpriseAdd(url('enterprise/edit')); 
        // 添加一个隐藏字段到表单
        $form->add(QForm::ELEMENT, 'enterprise_id', array('_ui' => 'hidden'));

        if ($this->_context->isPOST() && $form->validate($_POST))
        {
            $enterprise->changeProps($form->values());
            $enterprise->save();
            return $this->_redirect(url('enterprise/index'));
        }
        elseif (!$this->_context->isPOST())
        {
            $form->import($enterprise);
        }

        // 将表单对象传递给视图
        $this->_view['form'] = $form;

        $this->_viewname = 'Add';
    }

    function actionSetting()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }

        $user = $this->_app->currentUserObject();
        if(2 != $user->permission_id)
        {
            return $this->_redirect(url('default/index'));
        }
        $enterprise = Enterprise::find('enterprise_id = ?', $user->enterprise_id)->query();

        if($enterprise->id() != $user->enterprise_id)
        {
            return $this->_redirect(url('default/index'));
        }

        if(isset($_POST['enterprise_name']) && isset($_POST['enterprise_desc']))
        {
            $enterprise->enterprise_name  = $_POST['enterprise_name'];
            $enterprise->enterprise_desc  = $_POST['enterprise_desc'];

	    $web_site=Q::ini('appini/web_site_ip');

            if($_POST['uploadpic'])
            {
                $enterprise->enterprise_logo = $web_site. $_POST['uploadpic'];
            }
            else if(! $enterprise->enterprise_logo)
            {
                $web_site=Q::ini('appini/web_site_ip');
                $default_logo = $web_site. $this->_context->baseDir() .'static/const_img/telecom_logo.png';
                $enterprise->enterprise_logo = $default_logo;
            }
            $enterprise->save();	
            return $this->_redirectMessage(
                '企业信息设置成功',
                '企业信息设置成功',
                url('default/index'));
        }

        $this->_view['enter'] = $enterprise;
        $this->_view['baseurl'] =$this->_context->baseDir();
        $this->_viewname = 'setting';
    }

    function actionRequireEnterLogo()
    {
        if(!isset($this->_context->user_name))
        {
            return 'failed';  
        }
        $cur_user = User::find('username = ?', $this->_context->user_name)->query();
        if($cur_user->username != $this->_context->user_name)
        {
            return 'failed';
        }
        $enterprise = Enterprise::find('enterprise_id = ?', $cur_user->enterprise_id)->query();
        if($enterprise->id() == $cur_user->enterprise_id)
        {
            $web_site=Q::ini('appini/web_site_ip');
            $str = 'enterprise_name='.$enterprise->enterprise_name;
            if(strlen($enterprise->enterprise_logo) > 0)
            {
                $str .= '\r\nenterprise_logo='.$enterprise->enterprise_logo;
            }
            else
            {
                $web_site=Q::ini('appini/web_site_ip');
                $str .= '\r\nenterprise_logo='.$web_site.$this->_context->baseDir().'static/const_img/default.png';
            }
            return $str;
        }
        return 'failed';
    }

    function actionRequireEnterLogoEx()
    {
        if(!isset($this->_context->user_name))
        {
            return 'failed';  
        }
        $cur_user = User::find('username = ?', $this->_context->user_name)->query();
        if(intval($cur_user->username) != intval($this->_context->user_name))
        {
            //dump($cur_user->username);
            //dump($this->_context->user_name);
            return 'failed';
        }

        $enterprise = Enterprise::find('enterprise_id = ?', $cur_user->enterprise_id)->query();
        //dump($cur_user->enterprise_id);
        if($enterprise->id() == $cur_user->enterprise_id)
        {
            //dump($enterprise);
            $web_site=Q::ini('appini/web_site_ip');
            $str = 'enterprise_name='.$enterprise->enterprise_name;
            if(strlen($enterprise->enterprise_logo) > 0)
            {
                $str .= '\r\nenterprise_logo='.$enterprise->enterprise_logo;
            }
            else
            {
                $web_site=Q::ini('appini/web_site_ip');
                $str .= '\r\nenterprise_logo='.$web_site.$this->_context->baseDir().'static/const_img/default.png';
            }
            $str .= '\r\nenterprise_id='.$cur_user->enterprise_id;
            return $str;
        }
        return 'failed';
    }
    
    function actionUploadedimage()
    {
        if(null == $this->_app->currentUser())
        {
            echo "err";
        }
        else
        {
            QLog::log('start to load image');  
            $fileElementName = "fileToUpload";

            $error = "";
            $msg = "";
            $fileElementName = 'fileToUpload';
            if(!empty($_FILES[$fileElementName]['error']))
            {
                switch($_FILES[$fileElementName]['error'])
                {
                case '1':
                    $error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                    $error_code = 101;
                    return;
                    break;
                case '2':
                    $error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                    $error_code = 102;
                    return;
                    break;
                case '3':
                    $error = 'The uploaded file was only partially uploaded';
                    $error_code = 102;
                    return;
                    break;
                case '4':
                    $error = 'No file was uploaded.';
                    $error_code = 102;
                    return;
                    break;

                case '6':
                    $error = 'Missing a temporary folder';
                    $error_code = 102;
                    return;
                    break;
                case '7':
                    $error = 'Failed to write file to disk';
                    $error_code = 102;
                    return;
                    break;
                case '8':
                    $error = 'File upload stopped by extension';
                    $error_code = 102;
                    return;
                    break;
                case '999':
                default:
                    $error = 'No error code avaiable';
                }
            }
            elseif(empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none')
            {
                $error = 'No file was uploaded..';
                return;
            }
            else 
            {
                $msg .= " File Name: " . $_FILES['fileToUpload']['name'] . ", ";
                $msg .= " File Size: " . @filesize($_FILES['fileToUpload']['tmp_name']);
            }		

            $user = $this->_app->currentUserObject();
            $enterprise = Enterprise::find('enterprise_id = ?', $user->enterprise_id)->query();

            $time = time();
            $uploader = new Helper_Uploader();
            $file = $uploader->file($fileElementName);
            if($file->isSuccessed())
            {
                try{
                    if($file->isValid('jpg, jpeg, png, gif'))
                    {
                        $filepath = $this->_app->config('ROOT_DIR'). '/img/enter_log/' . date('Ym');
                        //echo "file:".$filepath;
                        $url_path = $this->_context->baseDir(). 'img/enter_log/' . date('Ym');

                        if(!file_exists($filepath))
                        {
                            mkdir($filepath);
                        }
                        if(file_exists($filepath.'/'.$time.$file->filename()))
                        {
                            unlink ( $filepath.'/'.$time.$file->filename() );
                        }
                        //$file->move($filepath.'/'.$time.$file->filename());
                        //$dst_file = Helper_Upload::makethumb($filepath.'/'.$time.$file->filename(), 48, 48, 64, 64);
                        //$dst_url_path = $url_path.'/'.$time.$file->filename().'.thumb.jpg';

                        $image = Helper_Image::createFromFile($file->filepath(), $file->extname());
                        $w = Q::ini('appini/enter_log_width');
                        $h = Q::ini('appini/enter_log_height');

                        $image->crop($w, $h);
                        $image->saveAsJpeg($filepath.'/'.$time.$file->filename());
                        $dst_file = $filepath.'/'.$time.$file->filename();


                        $image->destroy();
                        $file->unlink();

                        $retVal = "{success:'" .'/img/user/' . date('Ym') .'/'.$time.$file->filename() . "'}";
                        QLog::log('retVal:'.$retVal);
                        if(strlen($enterprise->enterprise_logo) > 0)
                        {							
                            if(file_exists($enterprise->enterprise_logo))
                            {
                                //echo "avatar_url:".$user->avatar_url;
                                unlink($enterprise->enterprise_logo);
                            }
                        }
                        if(strlen($dst_file) > 0 && file_exists($dst_file))
                        {	
                            //echo "dst_file:".$dst_file;
                            $enterprise->enterprise_logo = $url_path.'/'.$time.$file->filename();
                        }
                        else
                        {
                            $enterprise->enterprise_logo = null;
                        }
                        $enterprise->save();
                        $error_code = 100;

                        $retVal = "{success:'".$enterprise->enterprise_logo."'}";

                        return $retVal;
                    }
                    else 
                    {
                        $error='uploaded err';
                        $error_code = 105;
                    }
                }
                catch (Exception $ex)
                {				
                    $error='uploaded err';
                    $error_code = 102;
                }
                return;
            }
            echo "{";
            echo				"error: '" . $error . "',\n";
            echo				"error_code: '" . $error_code . "',\n";
            echo "}";

        }
    }

    function actionRecordInfor()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }

        $cur_user = $this->_app->currentUserObject();
        if(1 != $cur_user->permission_id)
        {
            return $this->_redirect(url('default/index'));
        }
        $enterprise = Enterprise::find('enterprise_id = ?', $this->_context->enterprise_id)->query();

        if($enterprise->id() != $this->_context->enterprise_id)
        {
            echo "kekekek";
            return;
            return $this->_redirect(url('default/index'));
        }
        //注册单位名称
        $this->_view['enterprise_name'] = $enterprise->enterprise_name;

        //注册单位用户数量        
        $select1 = User::find('enterprise_id = ? and permission_id <> 2', $this->_context->enterprise_id)->all();
        $this->_view['users_count'] = $select1->getCount();

        //注册单位在线用户数
        $time = intval(CURRENT_TIMESTAMP);
        $last_check_time = $time - Q::ini('appini/web_intervel_check_time')*60;//比last_check_time大的才为登录用户
        $select2 = User::find('enterprise_id = ? AND last_check_time > ?', $this->_context->enterprise_id, $last_check_time)->all();
        $this->_view['online_count'] = $select2->getCount();

        //注册单位的使用流量

        //注册单位活跃用户数量
        $select3 = User::find('enterprise_id = ? AND login_count > ?', $this->_context->enterprise_id, Q::ini('appini/web_cfg_top_user_login_time'))->all();
        $this->_view['top_count'] = $select3->getCount();
        
    }
}
